package babo.cd.physicalexperiment.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.photoview.OnPhotoTapListener;
import com.luck.picture.lib.photoview.PhotoView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import babo.cd.physicalexperiment.R;
import babo.cd.physicalexperiment.activity.ImagePagerActivity;
import babo.cd.physicalexperiment.utils.CenterCropRoundCornerTransform;
import babo.cd.physicalexperiment.utils.Out;


public class ImageDetailFragment extends Fragment {
	private String mImageUrl;
//	private ResizableImageView mImageView;
	private ProgressBar progressBar;
//	private PhotoViewAttacher mAttacher;
	private LinearLayout ll_save;
	private RelativeLayout rl_save, rl_cancle;
	public static Context ct2;
	Bitmap btBitmap;
	private static String myurl = "";
	String dydz;
	Handler hd;
	private PhotoView mPhotoView;
	private List<String> imglist=new ArrayList<String>();
	public static ImageDetailFragment newInstance(String imageUrl, Context ct) {
		final ImageDetailFragment f = new ImageDetailFragment();
		ct2 = ct;
		final Bundle args = new Bundle();
		args.putString("url", imageUrl);
		myurl=imageUrl;
		
		Out.out("当前图片URL==="+myurl);
		f.setArguments(args);

		return f;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mImageUrl = getArguments() != null ? getArguments().getString("url")
				: null;
		hd=new Handler();

	}
	public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];    
        int len = 0;    
        while( (len = inStream.read(buffer)) != -1 ){    
            outSteam.write(buffer, 0, len);    
        }    
        outSteam.close();    
        inStream.close();    
        return outSteam.toByteArray();    
} 
	
    public static void readAsFile(InputStream inSream, File file) throws Exception {
        FileOutputStream outStream = new FileOutputStream(file);
        byte[] buffer = new byte[1024];
        int len = -1;
        while( (len = inSream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inSream.close();
    }
	@Override
	public View onCreateView(final LayoutInflater inflater,
                             final ViewGroup container, Bundle savedInstanceState) {
		final View v = inflater.inflate(R.layout.image_detail_fragment,
				container, false);
//		mImageView = (ResizableImageView) v.findViewById(R.id.image);
		ll_save = (LinearLayout) v.findViewById(R.id.ll_save);
		rl_save = (RelativeLayout) v.findViewById(R.id.rl_save);
		rl_cancle = (RelativeLayout) v.findViewById(R.id.rl_cacel);
		mPhotoView = (PhotoView)v.findViewById(R.id.photoview);
		//设置缩放类型，默认ScaleType.CENTER（可以不设置）
		mPhotoView.setScaleType(ImageView.ScaleType.CENTER);
		mPhotoView.setOnLongClickListener(new OnLongClickListener() {
			@Override
			public boolean onLongClick(View view) {
								ll_save.setVisibility(View.VISIBLE);
				rl_save.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View arg0) {
			            new Thread(){
		                    public void run() {
		                        try {
		                            URL url = new URL(ImagePagerActivity.myurls[ImagePagerActivity.position]);
		                            Out.out("myurl-===="+myurl);
		                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		                            conn.setConnectTimeout(6*1000);  // 注意要设置超时，设置时间不要超过10秒，避免被android系统回收
		                            if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
		                            InputStream inSream = conn.getInputStream();
		                            //把图片保存到项目的根目录

		                        	String lj= Environment.getExternalStorageDirectory()+ File.separator+"Android/data/zhengmadoc/";
									File file = new File(lj);
									if (!file.exists()) {
										file.mkdirs();
									}
									final String fileName=new Date().getTime()
											+ ".jpg";
								final File img = new File(file, fileName);

		                            readAsFile(inSream, img);
		                            hd.post(new Runnable() {

										@Override
										public void run() {

											 try {
											        MediaStore.Images.Media.insertImage(ct2.getContentResolver(),
											        		img.getAbsolutePath(), fileName, null);
											    } catch (FileNotFoundException e) {
											        e.printStackTrace();
											    }
											    // 最后通知图库更新
											 ct2.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("/sdcard/Boohee/"+fileName))));
											    Out.toast(ct2,"成功保存本地图库！");
					                         ll_save.setVisibility(View.GONE);

										}
									});

		                        } catch (Exception e) {
		                            e.printStackTrace();
		                        }
		                    };
		                }.start();
						Out.toast(ct2,"正在下载~");
                        ll_save.setVisibility(View.GONE);
					}
				});
				rl_cancle.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View arg0) {
						ll_save.setVisibility(View.GONE);

					}
				});
				return true;
			}
		});

		mPhotoView.setOnPhotoTapListener(new OnPhotoTapListener() {
			@Override
			public void onPhotoTap(ImageView view, float x, float y) {
				getActivity().finish();
			}
		});
		RequestOptions options = RequestOptions.bitmapTransform(new CenterCropRoundCornerTransform(1));
		options.fitCenter();
		Glide.with(getContext())
				.load(mImageUrl)
//				.placeholder(R.mipmap.ic_launcher)//加载过程中图片未显示时显示的本地图片
//				.error(R.mipmap.ic_launcher)//加载异常时显示的图片
////  .centerCrop()//图片图填充ImageView设置的大小
//				.fitCenter()//缩放图像测量出来等于或小于ImageView的边界范围,该图像将会完全显示
				.apply(options)
				.into(mPhotoView);
//		mAttacher = new PhotoViewAttacher(mImageView);
//		mAttacher.setOnLongClickListener(new OnLongClickListener() {
//
//			@Override
//			public boolean onLongClick(View arg0) {
//				ll_save.setVisibility(View.VISIBLE);
//				rl_save.setOnClickListener(new View.OnClickListener() {
//
//					@Override
//					public void onClick(View arg0) {
//			            new Thread(){
//		                    public void run() {
//		                        try {
//		                            URL url = new URL(ImagePagerActivity.myurls[ImagePagerActivity.position]);
//		                            Out.out("myurl-===="+myurl);
//		                            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//		                            conn.setConnectTimeout(6*1000);  // 注意要设置超时，设置时间不要超过10秒，避免被android系统回收
//		                            if (conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");
//		                            InputStream inSream = conn.getInputStream();
//		                            //把图片保存到项目的根目录
//
//		                        	String lj= Environment.getExternalStorageDirectory()+ File.separator+"Android/data/zhengmadoc/";
//									File file = new File(lj);
//									if (!file.exists()) {
//										file.mkdirs();
//									}
//									final String fileName=new Date().getTime()
//											+ ".jpg";
//								final File img = new File(file, fileName);
//
//		                            readAsFile(inSream, img);
//		                            hd.post(new Runnable() {
//
//										@Override
//										public void run() {
//
//											 try {
//											        MediaStore.Images.Media.insertImage(ct2.getContentResolver(),
//											        		img.getAbsolutePath(), fileName, null);
//											    } catch (FileNotFoundException e) {
//											        e.printStackTrace();
//											    }
//											    // 最后通知图库更新
//											 ct2.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(new File("/sdcard/Boohee/"+fileName))));
//											    Out.toast(ct2,"成功保存本地图库！");
//					                         ll_save.setVisibility(View.GONE);
//
//										}
//									});
//
//		                        } catch (Exception e) {
//		                            e.printStackTrace();
//		                        }
//		                    };
//		                }.start();
//						Out.toast(ct2,"正在下载~");
//                        ll_save.setVisibility(View.GONE);
//					}
//				});
//				rl_cancle.setOnClickListener(new View.OnClickListener() {
//
//					@Override
//					public void onClick(View arg0) {
//						ll_save.setVisibility(View.GONE);
//
//					}
//				});
//
//				return false;
//			}
//		});
//		mAttacher.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
//
//			@Override
//			public void onPhotoTap(View arg0, float arg1, float arg2) {
//				getActivity().finish();
//			}
//		});

		progressBar = (ProgressBar) v.findViewById(R.id.loading);
		return v;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);


//		Glide
//				.with(getActivity())
//				.load(mImageUrl)
//
//				.into(mImageView);


//		ImageLoader.getInstance().displayImage(mImageUrl, mImageView,
//				new SimpleImageLoadingListener() {
//					@Override
//					public void onLoadingStarted(String imageUri, View view) {
//						progressBar.setVisibility(View.VISIBLE);
//					}
//
//					@Override
//					public void onLoadingFailed(String imageUri, View view,
//							FailReason failReason) {
//						String message = null;
//						switch (failReason.getType()) {
//						case IO_ERROR:
//							message = "下载错误";
//							break;
//						case DECODING_ERROR:
//							message = "图片无法显示";
//							break;
//						case NETWORK_DENIED:
//							message = "网络有问题，无法下载";
//							break;
//						case OUT_OF_MEMORY:
//							message = "图片太大无法显示";
//							break;
//						case UNKNOWN:
//							message = "未知的错误";
//							break;
//						}
//					try {
//						Toast.makeText(getActivity(), message,
//								Toast.LENGTH_SHORT).show();
//					} catch (Exception e) {
//						// TODO: handle exception
//					}
//						progressBar.setVisibility(View.GONE);
//					}
//
//					@Override
//					public void onLoadingComplete(String imageUri, View view,
//							Bitmap loadedImage) {
//						progressBar.setVisibility(View.GONE);
//						mAttacher.update();
//					}
//				});

	}
	protected boolean saveBitmap2File(Bitmap bmp, File img) {
		CompressFormat format = CompressFormat.JPEG;
		int quality = 100;
		OutputStream stream = null;
		try {
			stream = new FileOutputStream(img);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return bmp.compress(format, quality, stream);
	}
	private void getImgByUrl(String url2) {
		byte[] data=null;
		try {
			data = readInputStream(new URL(url2).openStream());
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	    Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0,
	            data.length);  
	    String lj= Environment.getExternalStorageDirectory()+ File.separator+"Android/data/zhengma/";
		File file = new File(lj);
		if (!file.exists()) {
			file.mkdirs();
		}
		File img = new File(file, new Date().getTime()
				+ ".jpg");
	    try {
			bitmap.compress(CompressFormat.JPEG, 100, new FileOutputStream(
					img));
			Out.toast(ct2, "成功保存到"+img.getAbsolutePath());
			ll_save.setVisibility(View.GONE);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
	

	
	public static void saveImageToGallery(Context context, Bitmap bmp) {
	    // 首先保存图片
	 
	    
	    // 其次把文件插入到系统图库
	    
	}
}
